import express from 'express';
import { promises as fs } from 'fs';
import path from 'path';
import OSS from 'ali-oss';
import { v4 as uuidv4 } from 'uuid';

const router = express.Router();

// 读取travels.json文件
async function readTravelsFile() {
    const filePath = path.join(__dirname, '../data/travels.json');
    const data = await fs.readFile(filePath, 'utf8');
    return JSON.parse(data);
}

// 写入travels.json文件
async function writeTravelsFile(data: any) {
    const filePath = path.join(__dirname, '../data/travels.json');
    await fs.writeFile(filePath, JSON.stringify(data, null, 2));
}

// 创建OSS客户端
function createOSSClient(credentials: any) {
    return new OSS({
        region: 'oss-cn-beijing',
        bucket: 'wen-xuan',
        accessKeyId: credentials.AccessKeyId,
        accessKeySecret: credentials.AccessKeySecret,
        stsToken: credentials.SecurityToken,
        authorizationV4: true
    });
}

// 上传文件到OSS
async function uploadFileToOSS(client: any, file: any) {
    const timestamp = Date.now();
    const ext = path.extname(file.originalname);
    const filename = `${uuidv4()}${ext}`;
    const result = await client.put(
        `uploads/${filename}?t=${timestamp}`,
        file.buffer
    );
    return result.url;
}

// 创建新游记
router.post('/create', async (req, res) => {
    try {
        const { title, content, author } = req.body;
        const files = req.files as Express.Multer.File[];

        // 获取OSS凭证
        const credentials = await fetch('http://localhost:8085/api/oss/get_sts_token_for_oss_upload')
            .then(res => res.json());

        // 创建OSS客户端
        const client = createOSSClient(credentials);

        // 上传图片和视频
        const images = [];
        let video = null;

        for (const file of files) {
            const url = await uploadFileToOSS(client, file);
            if (file.mimetype.startsWith('image/')) {
                images.push(url);
            } else if (file.mimetype.startsWith('video/')) {
                video = url;
            }
        }

        // 创建新游记对象
        const newTravel = {
            id: Date.now().toString(),
            title,
            content,
            images,
            video,
            author,
            status: 'pending',
            rejectReason: null,
            isDeleted: false,
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString()
        };

        // 读取现有数据
        const travels = await readTravelsFile();

        // 添加新游记
        travels.push(newTravel);

        // 写入文件
        await writeTravelsFile(travels);

        res.status(201).json({
            code: 0,
            message: '游记创建成功',
            data: newTravel
        });

    } catch (error) {
        console.error('创建游记失败:', error);
        res.status(500).json({
            code: 500,
            message: '创建游记失败',
            error: error.message
        });
    }
});

export default router; 